<template>
  <div class="commentContent">
    <div class="clearBoth">
      <div class="head fl" @click="tabChange('comment')" :class="{'head_active': tabType === 'comment'}">{{$t('km.comment',{commentCount})}}</div>
      <div class="head fl" @click="tabChange('log')" :class="{'head_active': tabType === 'log'}">{{$t('km.logNum',{logCount})}}</div>
    </div>
    <div class="commentsBox">
      <div class="comment_0" v-if="!totalCount">{{tabType === 'comment' ? $t('km.noComments'): $t('km.nolog')}}</div>
      <div class="comments" v-if="totalCount">
        <div v-for="(item, index) in commentContentList" class="list" :key="index">
          <div class="com">
            <span class="agent">
              <img :src="item.imIcon" v-show="item.imIcon"/>
            </span>
            <div class="comment-text">
              <div class="textHead">
                <span class="userName">{{item.name}}</span>
                <span class="right_item">
                  <span class="time">{{item.updateTime}}</span>
                  <span class="deleteComment" @click="deleteComment(item, index)" v-if="item.ifSelf"><i class="icon iconfont icon-shanchu"></i></span>
                </span>
              </div>
              <div class="editor-content" v-html="item.content" @click.stop="imageClick">
              </div>
              <!--<big-image :imgInfo="bigImage" @closeImageDialog="closeBigImage"></big-image>-->
            </div>
          </div>
        </div>
        <div class="foldBtn">
          <span class="fold" v-if="iffold && onOff" @click="showList(2, true)"><i class="icon iconfont icon-shouqi"></i>{{tabType === 'comment' ? $t('km.foldComments'): $t('km.foldLogs')}}</span>
          <span class="unfold" v-if="!iffold && totalCount>2" @click="showList(totalCount, false)"><i class="icon iconfont icon-zhankai1"></i>{{$t('km.viewTotalComments')}}</span></div>
        </div>
    </div>
    <div class="commentEditor" v-show="isAdmin && tabType === 'comment'">
      <!--<quill-editor ref="editor"></quill-editor>-->
      <div id="editor_evaluation"></div>
      <el-button type="primary" @click="submitComment()" class="submitComment primary_btn">{{$t('km.submitComments')}}</el-button>
    </div>
  </div>
</template>
<script>
//  import quillEditor from '@/components/business-modules/km/km-detail/QuillEditor.vue'
  import {uploadTo7moorKmImgDomain, PasteImguploadTo7moorKmDomain} from '@/utils/qiniuUtils'
  import {getCurrentDate, filterXSS} from '@/utils/m7Utils'
  import BigImage from '@/components/public-modules/bigImage/BigImage'
  import Editor from 'wangeditor'
  import * as uuid from 'uuid'
  import { km } from '@/utils/cosUrl'
  import * as types from '@/store/mutation-types.js'
  export default {
    data () {
      return {
        tabType: 'comment',
        iffold: false,
        showTotal: true,
        commentContentList: [],
        totalCount: 0, // 当前激活tab总条数
        logCount: 0, // 日志总条数
        commentCount: 0, // 评论总条数
        bigImage: {
          bigImageShow: false,
          url: ''
        },
        wEditor: {},
        onOff: true,
        isSelf: false,
        m7uploaders: []
      }
    },
    computed: {
      isAdmin () {
        // 判断是否为超管，如果是，则评论只读，无法评论
        if (this.$store.state.session.user.isAdmin && this.$store.state.session.user.isAdmin === true) {
          return false
        }
        return true
      }
    },
    methods: {
      tabChange (type) {
        this.tabType = type
        this.showList(2, true)
      },
      deleteComment (item, index) {
        let data = {
          _id: item.id
        }
        this.$confirm(this.$t('monitor.deleteTips'), this.$t('public.delete'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('deleteTheComments', data).then((rep) => {
            if (rep.success) {
              this.$message({
                type: 'success',
                message: this.$t('km.deleteSucc')
              })
              if (this.iffold && this.onOff && this.totalCount > 3) {
                this.showList(this.totalCount + 1, false)
              } else {
                this.showList(2, true)
              }
            }
          })
        }).catch(() => {
        })
      },
      initUploadImageFile () {
        let account = this.$store.state.session.user.account
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function (up, file) {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          const sourceLink = km.getFileKey({up, info, file, isLink: true}) // 获取上传成功后的文件的Url
          // self.wEditor.txt.append('<img src="' + sourceLink + '" alt="">')
          // 改为图片在光标出插入
          self.wEditor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
        }
        let error = function (up, err, errTip) {
          if (errTip) {
            self.$message.error(errTip)
          }
          console.log('uploadError ' + errTip)
        }
        let key = function (up, file) {
          let date = getCurrentDate()
          let today = new Date()
          let time = today.getTime()
  //          let fileName = file.name
  //          let fileSuffix = ''
  //          if (fileName) {
  //            fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
  //          }
          let key = km.getCosKey(account + '/km/' + date + '/' + time + '/' + uuid.v1() + file.name)
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorKmImgDomain(this.$store.state.session.user._id, 'kmUploadImageFileComment', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
      },
      pasteImg (evnet) {
        let ele = evnet.clipboardData.items || []
        let account = this.$store.state.session.user.account
        let that = this
        for (let i = 0; i < ele.length; ++i) {
          if (ele.length === 1 && ele[i].kind === 'file' && ele[i].type.indexOf('image/') !== -1) {
            let blob = ele[i].getAsFile()
            let filename = 'clipboard' + new Date().getTime() + '.png'
            let key = function (up, file) {
              let date = getCurrentDate()
              let today = new Date()
              let time = today.getTime()
              //          let fileName = file.name
              //          let fileSuffix = ''
              //          if (fileName) {
              //            fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
              //          }
              let key = account + '/km/' + date + '/' + time + '/' + uuid.v1() + file.name
              return key
            }
            let key1 = key()
            let uploadProgress = function (up, file) {
            }
            let fileUploaded = function (up) {
              const sourceLink = km.getFileKey({up, file, isLink: true}) // 获取上传成功后的文件的Url
              // that.wEditor.txt.append('<img src="' + sourceLink + '" alt="">')
              // 改为图片在光标出插入
              that.wEditor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
//              that.sendChatMsg.content = sourceLink
//              that.handleSubmit({}, 'image')
//              that.uploaded.uploadImg = false
            }
            PasteImguploadTo7moorKmDomain(this.$store.state.session.user._id, blob, filename, uploadProgress, fileUploaded, key1)
          }
        }
      },
      submitComment () {
        let editorHtml = this.wEditor.txt.html()
        if (editorHtml === '<p><br></p>') {
          this.$message(this.$t('km.contentNotEmpty'))
          return
        }
        let data = {
          kmItemId: this.$store.state.km.ItemEditdata.row._id,
          kmType: this.$store.state.km.ItemEditdata.row.kmType,
          content: editorHtml
        }
        this.$store.dispatch('submitComments', data).then((rep) => {
          if (rep.success) {
            this.wEditor.txt.html('')
            if (this.iffold && this.onOff) {
              this.showList(this.totalCount + 1, false)
            } else {
              this.showList(2, true)
            }
          }
        })
      },
      showLogs (data, onlyUpdateCount) {
        this.$store.dispatch('getKmLogs', data).then((rep) => {
          if (rep.success) {
            this.logCount = rep.totalCount
            if (onlyUpdateCount) {
              return
            }
            this.totalCount = rep.totalCount
            this.commentContentList = []
            let agents = this.$agentsMap() || {}
            for (let i = 0; i < rep.list.length; i++) {
              let item = rep.list[i]
              let agent = agents[item.user]
              let content = item.content.map((one) => {
                let data = {}
                if (one.type === 'addFiles' || one.type === 'delFiles') {
                  data = {data: one.data && one.data.join(',')}
                } else if (one.type === 'changeTitle') {
                  data = {from: one.data[0], to: one.data[1]}
                } else if (one.type === 'changeCatalogue') {
                  data = {from: one.data[0], to: one.data[1]}
                }
                return this.$t('km.' + one.type, data)
              }).join('; ')
              this.commentContentList.push({
                id: item._id,
                content,
                updateTime: item.updateTime,
                name: agent && (agent.displayName + ' [' + agent.exten + ']'),
                imIcon: agent && agent.im_icon ? agent.im_icon + '?imageView2/1/w/50/h/50' : '',
                ifSelf: false
              })
            }
          }
        })
      },
      showList (pageSize, flag) {
        this.iffold = !flag
        if (this.totalCount > 2) {
          if (pageSize > 2) {
            this.onOff = true
          } else {
            this.onOff = false
          }
        } else {
          this.onOff = true
        }
        let data = {
          kmItemId: this.$store.state.km.ItemEditdata.row._id,
          kmType: this.$store.state.km.ItemEditdata.row.kmType,
          page: 1,
          limit: pageSize
        }
        if (this.tabType === 'comment') {
          this.showAllComments(data)
        } else {
          this.showLogs(data)
        }
      },
      showAllComments (data) {
        let commentId = this.$store.state.session.user._id
        this.$store.dispatch('getComments', data).then((rep) => {
          if (rep.success) {
            this.totalCount = rep.totalCount
            this.commentCount = rep.totalCount
            this.commentContentList = []
            let agents = this.$agentsMap() || {}
            for (let i = 0; i < rep.list.length; i++) {
              if (rep.list[i].content.indexOf('href="') !== -1 && rep.list[i].content.indexOf('href="http://') === -1 && rep.list[i].content.indexOf('href="https://') === -1) {
                rep.list[i].content = rep.list[i].content.split('href="').join('href="http://')
              }
              let agent = agents[rep.list[i].user] || {}
              if (rep.list[i].user === commentId) {
                this.commentContentList.push({
                  id: rep.list[i]._id,
                  content: filterXSS(rep.list[i].content.replace(/<img /g, '<img class="imgA"')),
                  updateTime: rep.list[i].updateTime,
                  name: agent.displayName + ' [' + agent.exten + ']',
                  imIcon: agent.im_icon ? agent.im_icon + '?imageView2/1/w/50/h/50' : '',
                  ifSelf: true
                })
              } else {
                this.commentContentList.push({
                  id: rep.list[i]._id,
                  content: filterXSS(rep.list[i].content.replace(/<img /g, '<img class="imgA"')),
                  updateTime: rep.list[i].updateTime,
                  name: agent.displayName + ' [' + agent.exten + ']',
                  imIcon: agent.im_icon ? agent.im_icon + '?imageView2/1/w/50/h/50' : '',
                  ifSelf: false
                })
              }
            }
          }
        }).then(() => {
          let contents = document.getElementsByClassName('editor-content')
          for (let j = 0; j < contents.length; j++) {
            let olList = contents[j].getElementsByTagName('ol')
            let ulList = contents[j].getElementsByTagName('ul')
            for (let i = 0; i < olList.length; i++) {
              olList[i].setAttribute('class', 'ollist')
            }
            for (let i = 0; i < ulList.length; i++) {
              ulList[i].setAttribute('class', 'ullist')
            }
          }
        })
      },
      imageClick (event) {
        if (event.target.tagName === 'IMG') {
          // 获取当前点击的图片的src
          let _url = event.target.src
          // 获取所有的图片列表
          let _array = this.$el.querySelectorAll('.commentContent .imgA')
          // 存放所有图片的信息
          let _list = []
          // 存放当前点击的图片的索引
          let _index = 0
          for (let i = 0; i < _array.length; i++) {
            if (_url === _array[i].src) {
              _index = i
            }
            let obj = {
              url: _array[i].src,
              id: _array[i].src,
              name: ''
            }
            _list.push(obj)
          }
          let msg = {
            show: true,
            url: _url,
            index: _index,
            list: _list
          }
          this.$store.commit(types.SET_BIGIMG, msg)
        }
        event.preventDefault()
        this.$nextTick(() => {
          if (event.target.nodeName.toLowerCase() === 'a') {
            let dom = event.target
            let domUrl = dom.getAttribute('href')
            try {
              window.open(domUrl, '_blank')
            } catch (e) {
              this.$message.error(this.$t('webchat.urlError'))
            }
          }
        })
      },
      closeBigImage () {
        this.bigImage.bigImageShow = false
        this.bigImage.url = ''
      },
      initEditor () {
        this.wEditor = new Editor('#editor_evaluation')
        this.wEditor.config.menus = [
          'head',  // 标题
          'bold',  // 粗体
          'fontSize',  // 字号
          'fontName',  // 字体
          'italic',  // 斜体
          'underline',  // 下划线
//          'strikeThrough',  // 删除线
//          'foreColor',  // 文字颜色
//          'backColor',  // 背景颜色
          'link',  // 插入链接
          'list',  // 列表
//          'justify',  // 对齐方式
//          'quote',  // 引用
//          'emoticon',  // 表情
          'table', // 表格
//          'code',  // 插入代码
          'undo',  // 撤销
          'redo'  // 重复
        ]
        this.wEditor.config.pasteTextHandle = filterXSS
        this.wEditor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
        this.wEditor.config.zIndex = 100
        let lang = window.langJson || {}
        let editLang = lang.wangeditor
        this.wEditor.config.lang = editLang
        this.wEditor.create()
        let div = document.createElement('div')
        div.className = 'w-e-menu'
        div.style.cssText = 'z-index:101;'
        let span = document.createElement('i')
        span.className = 'w-e-icon-image'
        span.id = 'kmUploadImageFileComment'
        div.appendChild(span)
        // document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
        document.querySelector('#editor_evaluation .w-e-toolbar').appendChild(div)
        this.initUploadImageFile()
        // demo 程序将粘贴事件绑定到 document 上
        let self = this
        // document.getElementsByClassName('w-e-text')[0].addEventListener('paste', self.pasteImg)
        document.querySelector('#editor_evaluation .w-e-toolbar').addEventListener('paste', self.pasteImg)
      }
    },
    mounted () {
//      let btn = document.getElementsByClassName('ql-kmUpLoadFile')[0]
//      let name = btn.className
//      btn.className = name + ' iconfont icon-tupianicon'
//      btn.id = 'kmUploadImageFile'
//      this.initUploadImageFile()
      this.initEditor()
      this.showList(2, true)
      let data = {
        kmItemId: this.$store.state.km.ItemEditdata.row._id,
        kmType: this.$store.state.km.ItemEditdata.row.kmType,
        page: 1,
        limit: 2
      }
      this.showLogs(data, true)
    },
    beforeDestroy () {
      this.m7uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    },
    components: {
//      quillEditor,
      BigImage
    }
  }
  // 深度有优先，遍历tree
  // function getNodeByKey (options = [], key, node = {}) {
  //   let isFind = options.some((item) => {
  //     if (item._id === key) {
  //       node = item
  //       return true
  //     } else if (item.childs && item.childs.length) {
  //       node = getKey(item.childs, key)
  //       return node
  //     }
  //   })
  //   if (isFind) {
  //     return node
  //   }
  // }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl";
  .commentContent
    .head
      font-weight bold
      margin-right 15px
      margin-bottom 15px
      &:hover
        cursor pointer
    .head_active
      color $c-main  
    .commentsBox
      .comment_0
        line-height 130px
        text-align center
      .comments
        .list
          margin 0px 0px 15px
          padding-bottom 15px
          overflow hidden
          border-bottom 1px solid $c-border1
          display flex
          .com
            width 100%
            position relative
            .agent
              display inline-block
              width 30px
              height 30px
              box-size(30px,30px)
              border-radius 15px
              background url("../../../public-modules/contact-summary/img/agent.png") no-repeat 50% 50%
              background-size 30px auto
              float left
              margin-right 12px
              flex 0 0 30px
              img
                width 30px
                border-radius 15px
                background-color $cf-white
            .comment-text
              float left
              width calc(100% - 50px)
              .textHead
                height 30px
                margin-right 12px
                line-height 30px
                .userName
                  float left
                  font-size 14px
                .right_item
                  width 140px
                  float right
                  .time
                    margin-right 10px
                    color $cf-gray4
                  .deleteComment
                    width 16px
                    height 16px
                    display inline-block
                    vertical-align middle
                    margin-bottom 20px
                  .deleteComment .icon
                    display none
                    color $c-pink
                    cursor pointer
        .foldBtn
          color $c-main
          font-size 14px
          margin-bottom 20px
          text-align right
          span
            cursor pointer
            .icon
              font-weight lighter
              line-height 14x
              padding-right 5px
    .commentEditor
      height 100px
      .submitComment
        margin 20px 0 74px 0
        float right
  .commentContent .commentsBox .comments .list:hover .com .comment-text .textHead .right_item .deleteComment .icon
    display inline
</style>
